package com.hlg.xboot.web.controller.mobile;

import com.hlg.xboot.core.annotation.JsonExclude;
import com.hlg.xboot.enums.Status;
import com.hlg.xboot.exceptions.*;
import com.hlg.xboot.model.modules.User;
import com.hlg.xboot.service.modules.UserService;
import com.hlg.xboot.utils.SMSHelper;
import com.hlg.xboot.vo.RestBody;
import com.hlg.xboot.web.controller.RestBaseMobileController;
import com.digi_zones.common.aliyun.oss.OSSService;
import com.digi_zones.common.utils.CommonUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.Serializable;

/**
 * <p>Description:用户接口</p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 *
 * @author yangxin
 * @version 1.0
 * @date 2016/10/25
 */
@RestController("userControllerMobile")
@RequestMapping("/mobile/user")
public class UserController extends RestBaseMobileController<User, UserService> {

    @Autowired
    private SMSHelper smsHelper;
    @Autowired
    private OSSService ossService;

    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @throws Exception
     */
    @JsonExclude(values = {"lastLoginTime", "lastLoginIP"})
    @PostMapping(value = "/login")
    public RestBody login(String username, String password, HttpServletRequest request) throws Exception {
        User user = service.login(username, password, request);
        if (user.getStates() == Status.DISABLED.getValue()) {
            throw new ServerBizException("用户已失效", ErrorCode.LOGIN_ERROR);
        }
        saveLoginUser(user, request);
        return success(user, ErrorCode.LOGIN_SUCCESS);
    }

    /**
     * 退出登录
     * @param request
     * @throws Exception
     */
    @PostMapping(value = "/logout")
    public RestBody logout(HttpServletRequest request) throws Exception {
        removeLoginUser(request);
        return success();
    }

    /**
     * 校验短信验证码
     * @param request
     * @throws Exception
     */
    private void validateVerifyCode(HttpServletRequest request) throws Exception {
        String verifyCode = request.getParameter("verifyCode");
        String phone = request.getParameter("phone");
        String expectVerifyCode = smsHelper.getSmsVerifyCode(phone);
        if (expectVerifyCode == null) {
            throw new VerifyCodeException("验证码已过期，请重新获取");
        }
        if (!expectVerifyCode.equals(verifyCode)) {
            throw new VerifyCodeException("验证码不正确");
        }
    }

    /**
     * 注册
     * @param user 用户注册信息
     * @param result
     * @throws Exception
     */
    @JsonExclude(values = {"lastLoginTime", "lastLoginIP"})
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public RestBody register(@Valid User user, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.validateVerifyCode(request);
        user = service.add(user);
        saveLoginUser(user, request);
        return success(user, ErrorCode.REGISTER_SUCCESS);
    }

    /**
     * 重置密码
     * @param phone         手机号
     * @param password      密码
     * @param verifyCode    验证码
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/reset_password", method = RequestMethod.POST)
    public RestBody resetPassword(String phone,String password, String verifyCode, HttpServletRequest request) throws Exception {
        if (StringUtils.isEmpty(phone)) {
            throw new ParameterException("手机号不能为空");
        }

        if (StringUtils.isEmpty(password)) {
            throw new ParameterException("密码不能为空");
        }

        if (StringUtils.isEmpty(verifyCode)) {
            throw new ParameterException("验证码不能为空");
        }

        this.validateVerifyCode(request);

        User user = service.findByPhone(phone);
        if (user == null) {
            throw new RecordNotFoundException("该手机号未绑定任何用户");
        }

        user.setPassword(DigestUtils.md5Hex(password));
        service.update(user);

        return success();
    }

    /**
     * 更新头像
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/avatar", consumes = {"multipart/form-data"})
    public RestBody updateAvatar(MultipartFile file, HttpServletRequest request) throws Exception {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileName = CommonUtils.genUUID() + "." + extension;
        String avatar = ossService.uploadImage(file.getInputStream(),fileName);
        User user = getLoginUser(request);
        user.setAvatar(avatar);
        service.update(user);
        saveLoginUser(user, request);
        return success(avatar);
    }

    @Override
    public RestBody updateField(@PathVariable Serializable id, @PathVariable String name, @PathVariable String value, HttpServletRequest request) throws Exception {
        User model = (User) service.findById(id);
        setFieldValue(model, name, value);
        service.update(model);
        saveLoginUser(model, request);
        return success();
    }
}
